#include <linux/cdev.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/mutex.h>
#include <linux/wait.h>
#include <linux/sched.h>

#define GLOBALFIFO_SIZE 0x1000
#define MEM_CLEAR 0x1
#define GLOBALFIFO_MAJOR 231

static int globalfifo_major = GLOBALFIFO_MAJOR;
module_param(globalfifo_major, int, S_IRUGO);

struct globalfifo_dev
{
	struct cdev cdev;
	unsigned int current_len;
	unsigned char mem[GLOBALFIFO_SIZE];
	struct mutex mutex;
	wait_queue_head_t r_wait;
	wait_queue_head_t w_wait;
};
struct globalfifo_dev *globalfifo_devp;

static loff_t globalfifo_llseek(struct file *filp, loff_t offset, int orig);
static long globalfifo_ioctl(struct file *filp, unsigned int cmd,
							 unsigned long arg);
static int globalfifo_open(struct inode *inode, struct file *filp);
static int globalfifo_release(struct inode *inode, struct file *filp);
static int globalfifo_read(struct file *filp, char __user *buf, size_t size,
						   loff_t *ppos);
static int globalfifo_write(struct file *filp, const char __user *buf,
							size_t size, loff_t *ppos);

static int globalfifo_open(struct inode *inode, struct file *filp)
{
	filp->private_data = globalfifo_devp;
	return 0;
}
static int globalfifo_release(struct inode *inode, struct file *filp)
{
	return 0;
}
static long globalfifo_ioctl(struct file *filp, unsigned int cmd,
							 unsigned long arg)
{
	struct globalfifo_dev *dev = filp->private_data;
	switch (cmd)
	{
	case MEM_CLEAR:
		mutex_lock(&dev->mutex);
		memset(dev->mem, 0, GLOBALFIFO_SIZE);
		mutex_unlock(&dev->mutex);
		printk(KERN_INFO "globalfifo is set to zero\n");
		break;
	default:
		return -EINVAL;
	}
	return 0;
}
static ssize_t globalfifo_read(struct file *filp, char __user *buf,
							   size_t count, loff_t *ppos)
{
	int ret;
	struct globalfifo_dev *dev = filp->private_data; // 获取设备结构体
	DECLARE_WAITQUEUE(wait, current);				 // 声明等待队列项

	mutex_lock(&dev->mutex);			 // 加锁保护设备数据
	add_wait_queue(&dev->r_wait, &wait); // 将当前进程添加到读取等待队列

	// 如果设备当前长度为 0，进入等待
	while (dev->current_len == 0)
	{
		// 如果文件以非阻塞模式打开，直接返回 -EAGAIN
		if (filp->f_flags & O_NONBLOCK)
		{
			ret = -EAGAIN;
			goto out;
		}
		__set_current_state(TASK_INTERRUPTIBLE); // 设置当前进程为可中断状态
		mutex_unlock(&dev->mutex);				 // 解锁
		schedule();								 // 调度其他进程运行

		// 如果当前进程被信号中断，返回 -ERESTARTSYS
		if (signal_pending(current))
		{
			ret = -ERESTARTSYS;
			goto out2;
		}
		mutex_lock(&dev->mutex); // 重新加锁
	}

	// 确保读取的字节数不超过设备当前长度
	if (count > dev->current_len)
		count = dev->current_len;

	// 将设备数据复制到用户空间
	if (copy_to_user(buf, dev->mem, count))
	{
		ret = -EFAULT; // 如果复制失败，返回 -EFAULT
		goto out;
	}
	else
	{
		// 移动设备内存数据，更新当前长度
		memcpy(dev->mem, dev->mem + count, dev->current_len - count);
		dev->current_len -= count;
		printk(KERN_INFO "read %d bytes(s), current_len:%d\n", count, dev->current_len);

		// 唤醒写等待队列中的进程
		wake_up_interruptible(&dev->w_wait);

		ret = count; // 返回读取的字节数
	}
out:
	mutex_unlock(&dev->mutex); // 解锁
out2:
	remove_wait_queue(&dev->r_wait, &wait); // 从读取等待队列中移除当前进程
	set_current_state(TASK_RUNNING);		// 恢复进程状态为运行状态
	return ret;
}

static ssize_t globalfifo_write(struct file *filp, const char __user *buf,
								size_t count, loff_t *ppos)
{
	struct globalfifo_dev *dev = filp->private_data; // 获取设备结构体
	int ret;
	DECLARE_WAITQUEUE(wait, current); // 声明等待队列项

	mutex_lock(&dev->mutex);			 // 加锁保护设备数据
	add_wait_queue(&dev->w_wait, &wait); // 将当前进程添加到写等待队列

	// 如果设备当前长度已满，进入等待
	while (dev->current_len == GLOBALFIFO_SIZE)
	{
		// 如果文件以非阻塞模式打开，直接返回 -EAGAIN
		if (filp->f_flags & O_NONBLOCK)
		{
			ret = -EAGAIN;
			goto out;
		}
		__set_current_state(TASK_INTERRUPTIBLE); // 设置当前进程为可中断状态
		mutex_unlock(&dev->mutex);				 // 解锁
		schedule();								 // 调度其他进程运行

		// 如果当前进程被信号中断，返回 -ERESTARTSYS
		if (signal_pending(current))
		{
			ret = -ERESTARTSYS;
			goto out2;
		}
		mutex_lock(&dev->mutex); // 重新加锁
	}

	// 确保写入的字节数不超过设备剩余空间
	if (count > GLOBALFIFO_SIZE - dev->current_len)
		count = GLOBALFIFO_SIZE - dev->current_len;

	// 从用户空间复制数据到设备内存
	if (copy_from_user(dev->mem + dev->current_len, buf, count))
	{
		ret = -EFAULT; // 如果复制失败，返回 -EFAULT
		goto out;
	}
	else
	{
		dev->current_len += count; // 更新设备当前长度
		printk(KERN_INFO "written %d byte(s), current_len = %d\n", count, dev->current_len);

		// 唤醒读等待队列中的进程
		wake_up_interruptible(&dev->r_wait);

		ret = count; // 返回写入的字节数
	}
out:
	mutex_unlock(&dev->mutex); // 解锁
out2:
	remove_wait_queue(&dev->w_wait, &wait); // 从写等待队列中移除当前进程
	set_current_state(TASK_RUNNING);		// 恢复进程状态为运行状态
	return ret;
}
static loff_t globalfifo_llseek(struct file *filp, loff_t offset, int orig)
{
	loff_t ret = 0;
	switch (orig)
	{
	case 0:
		if (offset < 0)
		{
			ret = -EINVAL;
			break;
		}
		if (offset > GLOBALFIFO_SIZE)
		{
			ret = -EINVAL;
			break;
		}
		filp->f_pos = (unsigned int)offset;
		ret = filp->f_pos;

		break;
	case 1:
		if ((filp->f_pos + offset) > GLOBALFIFO_SIZE)
		{
			ret = -EINVAL;
			break;
		}
		if ((filp->f_pos + offset) < 0)
		{
			ret = -EINVAL;
			break;
		}
		filp->f_pos += offset;
		ret = filp->f_pos;
		break;
	default:
		ret = -EINVAL;
		break;
	}
	return -EINVAL;
}
static const struct file_operations globalfifo_fops = {
	.owner = THIS_MODULE,
	.llseek = globalfifo_llseek,
	.read = globalfifo_read,
	.write = globalfifo_write,
	.unlocked_ioctl = globalfifo_ioctl,
	.open = globalfifo_open,
	.release = globalfifo_release,
};

static void globalfifo_setup_cdev(struct globalfifo_dev *dev, int index)
{
	int err, devno = MKDEV(globalfifo_major, index);

	cdev_init(&dev->cdev, &globalfifo_fops);
	dev->cdev.owner = THIS_MODULE;
	err = cdev_add(&dev->cdev, devno, 1);
	if (err)
		printk(KERN_NOTICE "Error %d adding globalfifo %d", err, index);
}
static int __init globalfifo_init(void)
{
	int ret;
	dev_t devno = MKDEV(globalfifo_major, 0);
	printk(KERN_INFO "globalfifo_init!\n");
	if (globalfifo_major)
		ret = register_chrdev_region(devno, 1, "globalfifo");
	else
	{
		ret = alloc_chrdev_region(&devno, 0, 1, "globalfifo");
		globalfifo_major = MAJOR(devno);
	}
	if (ret < 0)
		return ret;

	globalfifo_devp = kzalloc(sizeof(struct globalfifo_dev), GFP_KERNEL);
	if (!globalfifo_devp)
	{
		ret = -ENOMEM;
		goto fail_malloc;
	}

	globalfifo_setup_cdev(globalfifo_devp, 0);
	mutex_init(&globalfifo_devp->mutex);
	init_waitqueue_head(&globalfifo_devp->r_wait);
	init_waitqueue_head(&globalfifo_devp->w_wait);
	return 0;
fail_malloc:
	unregister_chrdev_region(devno, 1);
	return ret;
}

module_init(globalfifo_init);
static void __exit globalfifo_exit(void)
{
	printk(KERN_INFO "globalfifo_exit!\n");
	cdev_del(&globalfifo_devp->cdev);
	kfree(globalfifo_devp);
	unregister_chrdev_region(MKDEV(globalfifo_major, 0), 1);
}
module_exit(globalfifo_exit);
MODULE_AUTHOR("ARNO");
MODULE_LICENSE("GPL v2");
